const router = require('express').Router();

const db = require("../db.js")

// 侧边导航
router.get("/classify", (req, res) => {
    db.query("SELECT * FROM classify", (error, data) => {
        if (error) {
            res.json({
                "code": "400"
            })
        } else {
            res.json({
                "code": "200",
                "data": data
            })
        }
    })
})

// 小字
router.get("/classify_sub", (req, res) => {
    let id = req.query.id
    db.query('SELECT a.sub_name,a.sub_id FROM classify_sub a WHERE a.classify_id=?', id, (error, data) => {
        if (error) {
            res.json({
                "code": "400"
            })
        } else {
            res.json({
                "code": "200",
                "data": data
            })
        }
    })
})
// SELECT * FROM classify_sub a, classify b WHERE a.classify_id=b.classify_id

// 图片、文字
router.get("/classify_content", (req, res) => {
    let ids = req.query.ids.split(",")
    // console.log(ids[0]);

    let rests = []
    // console.log(ids);
    ids.forEach((element, index) => {
        // console.log(Number(element));
        db.query('SELECT content_image,content_text,sub_id FROM classify_content WHERE sub_id = ?', Number(element), (error, data) => {
            if (error) {
                console.log(error)
            } else {
                // console.log(data);
                rests.push(data)
                if (index + 1 == ids.length) {
                    res.json({
                        'data': rests
                    })
                }
            }
        })
    });

})

// SELECT a.content_image,a.content_text FROM classify_content a,classify_sub b WHERE a.sub_id=b.sub_id

module.exports = router;